package com.shiningstars.service;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;

import com.shiningstars.R;
import com.shiningstars.activity.AdminActivity;
import com.shiningstars.activity.AdminActivity.HandlerText;
import com.shiningstars.activity.SplashPageActivity;
import com.shiningstars.database.DatabaseHandler;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.php.WebHelper;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.valuebeans.Feedback;

@SuppressLint("SimpleDateFormat")
public class AdminFeedbackService extends Service implements Constants, Config, Messages {

	int attempts = SERVICE_ATTEMPTS;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		try {
			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

			List<String> adminCenterList = new ArrayList<String>();
			Set<String> centerIdSet = Utilities.getSharedPreferenceSet(getApplicationContext(), ADMIN_CENTERS);

			if (null != centerIdSet) {
				for (String centerId : centerIdSet) {
					String centerName = Utilities.getSharedPreference(getApplicationContext(), centerId);
					adminCenterList.add(centerName);
				}
			}

			StringBuilder sb = new StringBuilder();
			if (!Utilities.isBlankList(adminCenterList)) {
				for (String centerName : adminCenterList) {
					sb.append(SINGLE_QUOTE);
					sb.append(centerName);
					sb.append(SINGLE_QUOTE);
					sb.append(COMMA);
				}

				sb.deleteCharAt(sb.length() - 1);
			}

			final String centerNames = sb.toString().trim();

			new Thread() {
				@Override
				public void run() {

					Looper.prepare();
					DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());

					while (attempts > 0) {
						attempts--;
						while (true) {
							List<Long> feedbackIdList = databaseHandler.getFeedbackIdList(centerNames);

							StringBuilder sb = new StringBuilder();
							if (!Utilities.isBlankList(feedbackIdList)) {
								for (Long feedbackId : feedbackIdList) {
									sb.append(SINGLE_QUOTE);
									sb.append(feedbackId);
									sb.append(SINGLE_QUOTE);
									sb.append(COMMA);
								}

								sb.deleteCharAt(sb.length() - 1);
							}

							String feedbackIds = sb.toString().trim();

							try {
								WebHelper webHelper = new WebHelper();
								JSONObject json = webHelper.getAdminFeedback(feedbackIds, centerNames,
										getApplicationContext());

								if (null != json && json.getBoolean(SUCCESS)) {

									Calendar calendar = Calendar.getInstance();
									int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

									if (dayOfWeek < 7) {
										calendar.add(Calendar.DAY_OF_WEEK, -1 * dayOfWeek);
									}

									DateFormat df = new SimpleDateFormat(EEE);
									String day = df.format(calendar.getTime());

									String pathshalaDate1 = BLANK;
									String pathshalaDate2 = BLANK;

									if (SATURDAY.equals(day)) {
										pathshalaDate1 = Utilities.getDate(calendar.get(Calendar.DATE),
												calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR));

										calendar.add(Calendar.DAY_OF_WEEK, 1);

										pathshalaDate2 = Utilities.getDate(calendar.get(Calendar.DATE),
												calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR));
									}

									boolean notify = true;
									int count = json.getInt(FEEDBACK_COUNT);

									for (int i = 1; i <= count; i++) {
										JSONObject feedbackJSON = json.getJSONObject(FEEDBACK + _ + i);

										Feedback feedback = new Feedback();
										feedback.setFeedbackId(feedbackJSON.getLong(FEEDBACK_ID));
										feedback.setId(feedbackJSON.getLong(ID));
										feedback.setMobileNumber(feedbackJSON.getString(MOBILE_NUMBER));
										feedback.setImeiNumber(feedbackJSON.getString(IMEI_NUMBER));
										feedback.setMode(feedbackJSON.getString(MODE));
										feedback.setIsSynced(feedbackJSON.getString(IS_SYNCED));
										feedback.setIsNotified(feedbackJSON.getString(IS_NOTIFIED));

										String pathshalaDate = feedbackJSON.getString(QUESTION + "3");

										if (pathshalaDate.equals(pathshalaDate1)
												|| pathshalaDate.equals(pathshalaDate2)) {
											feedback.setIsRead(N);
										} else {
											feedback.setIsRead(Y);
										}

										feedback.setQuestion1(feedbackJSON.getString(QUESTION + "1"));
										feedback.setQuestion2(feedbackJSON.getString(QUESTION + "2"));
										feedback.setQuestion3(feedbackJSON.getString(QUESTION + "3"));
										feedback.setQuestion4(feedbackJSON.getString(QUESTION + "4"));
										feedback.setQuestion5(feedbackJSON.getString(QUESTION + "5"));
										feedback.setQuestion6(feedbackJSON.getString(QUESTION + "6"));
										feedback.setQuestion7(feedbackJSON.getString(QUESTION + "7"));
										feedback.setQuestion8(feedbackJSON.getString(QUESTION + "8"));
										feedback.setQuestion9(feedbackJSON.getString(QUESTION + "9"));
										feedback.setQuestion10(feedbackJSON.getString(QUESTION + "10"));
										feedback.setQuestion11(feedbackJSON.getString(QUESTION + "11"));
										feedback.setQuestion12(feedbackJSON.getString(QUESTION + "12"));
										feedback.setQuestion13(feedbackJSON.getString(QUESTION + "13"));
										feedback.setQuestion14(feedbackJSON.getString(QUESTION + "14"));
										feedback.setQuestion15(feedbackJSON.getString(QUESTION + "15"));
										feedback.setQuestion16(feedbackJSON.getString(QUESTION + "16"));
										feedback.setQuestion17(feedbackJSON.getString(QUESTION + "17"));
										feedback.setQuestion18(feedbackJSON.getString(QUESTION + "18"));
										feedback.setQuestion19(feedbackJSON.getString(QUESTION + "19"));
										feedback.setQuestion20(feedbackJSON.getString(QUESTION + "20"));
										feedback.setQuestion21(feedbackJSON.getString(QUESTION + "21"));
										feedback.setQuestion22(feedbackJSON.getString(QUESTION + "22"));
										feedback.setQuestion23(feedbackJSON.getString(QUESTION + "23"));
										feedback.setQuestion24(feedbackJSON.getString(QUESTION + "24"));
										feedback.setQuestion25(feedbackJSON.getString(QUESTION + "25"));
										feedback.setQuestion26(feedbackJSON.getString(QUESTION + "26"));
										feedback.setQuestion27(feedbackJSON.getString(QUESTION + "27"));
										feedback.setQuestion28(feedbackJSON.getString(QUESTION + "28"));
										feedback.setQuestion29(feedbackJSON.getString(QUESTION + "29"));
										feedback.setQuestion30(feedbackJSON.getString(QUESTION + "30"));
										feedback.setQuestion31(feedbackJSON.getString(QUESTION + "31"));
										feedback.setQuestion32(feedbackJSON.getString(QUESTION + "32"));
										feedback.setQuestion33(feedbackJSON.getString(QUESTION + "33"));
										feedback.setQuestion34(feedbackJSON.getString(QUESTION + "34"));
										feedback.setQuestion35(feedbackJSON.getString(QUESTION + "35"));
										feedback.setQuestion36(feedbackJSON.getString(QUESTION + "36"));
										feedback.setQuestion37(feedbackJSON.getString(QUESTION + "37"));
										feedback.setQuestion38(feedbackJSON.getString(QUESTION + "38"));
										feedback.setQuestion39(feedbackJSON.getString(QUESTION + "39"));
										feedback.setQuestion40(feedbackJSON.getString(QUESTION + "40"));
										feedback.setQuestion41(feedbackJSON.getString(QUESTION + "41"));
										feedback.setQuestion42(feedbackJSON.getString(QUESTION + "42"));
										feedback.setQuestion43(feedbackJSON.getString(QUESTION + "43"));
										feedback.setQuestion44(feedbackJSON.getString(QUESTION + "44"));
										feedback.setQuestion45(feedbackJSON.getString(QUESTION + "45"));
										feedback.setQuestion46(feedbackJSON.getString(QUESTION + "46"));
										feedback.setQuestion47(feedbackJSON.getString(QUESTION + "47"));
										feedback.setQuestion48(feedbackJSON.getString(QUESTION + "48"));
										feedback.setQuestion49(feedbackJSON.getString(QUESTION + "49"));
										feedback.setQuestion50(feedbackJSON.getString(QUESTION + "50"));
										feedback.setQuestion51(feedbackJSON.getString(QUESTION + "51"));
										feedback.setQuestion52(feedbackJSON.getString(QUESTION + "52"));
										feedback.setQuestion53(feedbackJSON.getString(QUESTION + "53"));
										feedback.setQuestion54(feedbackJSON.getString(QUESTION + "54"));

										databaseHandler.saveFeedback(feedback);

										if (notify) {
											notify = false;

											Intent intent = new Intent(getApplicationContext(),
													SplashPageActivity.class);

											PendingIntent pendingIntent = PendingIntent.getActivity(
													getApplicationContext(), 0, intent, 0);

											Uri notificationSound = RingtoneManager
													.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

											long pattern[] = { 0, 100, 200, 300, 400 };

											NotificationCompat.Builder builder = new NotificationCompat.Builder(
													getApplicationContext()).setContentTitle(SSP)
													.setSmallIcon(R.drawable.ic_launcher)
													.setContentIntent(pendingIntent).setAutoCancel(true)
													.setSound(notificationSound).setVibrate(pattern);

											builder.setContentText(NEW_FEEDBACK_RECEIVED);
											NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
											notificationManager.notify(0, builder.build());
										}

										HandlerText handlerText = AdminActivity.handlerText;
										if (null != handlerText) {
											Message message = handlerText.obtainMessage();
											message.obj = feedback;
											AdminActivity.handlerText.sendMessage(message);
										}
									}
								}
							} catch (JSONException e) {
								Utilities.logError(getApplicationContext(), AdminFeedbackService.class.getName(), e);
								break;
							} catch (IllegalStateException e) {
								Utilities.logError(getApplicationContext(), AdminFeedbackService.class.getName(), e);
								break;
							} catch (IOException e) {
								break;
							}

							break;
						}

						try {
							Thread.sleep(SERVICE_THREAD_SLEEP);
						} catch (Exception e) {
							Utilities.logError(getApplicationContext(), AdminFeedbackService.class.getName(), e);
							break;
						}
					}

					stopService(new Intent(getApplicationContext(), AdminFeedbackService.class));

					Looper.loop();
					Looper.myLooper().quit();
				}
			}.start();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), AdminFeedbackService.class.getName(), e);
		}

		return START_NOT_STICKY;
	}
}